// SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
// SPDX-License-Identifier: Mulan PSL v2
package data_report

import (
	"context"
	"encoding/json"
	"log"
	"time"

	"code.geniusai.org/notebook-manager/pkg/config"
	"code.geniusai.org/notebook-manager/pkg/entity"
	"github.com/apache/pulsar-client-go/pulsar"
)

func AsyncDataReportMsg(notebook *entity.Notebook, conf *config.Conf, action entity.Action) {
	asyncCh := make(chan error)
	go func() {
		asyncCh <- DataReportMsg(notebook, conf, action)
	}()
}

func DataReportMsg(notebook *entity.Notebook, conf *config.Conf, action entity.Action) error {
	log.Println("start report data to pulsar", notebook)
	// reportData to pulsar
	dataMsg := &entity.Data{
		EnvType:      conf.DataReport.EnvType,
		K8sNameSpace: notebook.UserID,
		ProjectId:    notebook.ProjectID,
		K8sPod:       notebook.Name + "-" + notebook.ID[len(notebook.ID)-5:] + "-0",
		Action:       action,
		UserName:     notebook.UserID,
		ReportDate:   time.Now().Format("2006-01-02 15:04:05"),
	}

	msg := &entity.NotebookReportMsg{
		ServiceName: entity.ReportDefaultValue.ServiceName,
		EventType:   entity.ReportDefaultValue.EventType,
		EventName:   entity.ReportDefaultValue.EventName,
		Data:        *dataMsg,
	}
	sendMsg(conf.DataReport.PulsarServiceUrl, conf.DataReport.NotebookTopic, msg)
	log.Println("success report data to pulsar", notebook)
	return nil
}

func sendMsg(serviceUrl string, topic string, msg *entity.NotebookReportMsg) {
	// 创建Pulsar客户端
	client, err := pulsar.NewClient(pulsar.ClientOptions{
		URL: serviceUrl,
	})
	if err != nil {
		log.Println(err)
		return
	}
	defer client.Close()

	// 创建Pulsar生产者
	producer, err := client.CreateProducer(pulsar.ProducerOptions{
		Topic: topic,
	})
	if err != nil {
		log.Println(err)
		return
	}
	defer producer.Close()

	// 将变量转换为JSON格式的字符串
	data, err := json.Marshal(msg)
	if err != nil {
		log.Println(err)
		return
	}

	// 发送消息
	log.Println("report data：\n", msg)
	_, err = producer.Send(context.Background(), &pulsar.ProducerMessage{Payload: data})
	if err != nil {
		log.Println("report data pulsar error ", err)
		return
	}
}
